package st.business.tepth.business.user.busnumber.workholder.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import st.business.tepth.R;
import st.business.tepth.business.bean.PartLocationBean;
import st.business.tepth.config.Url;
import st.business.tepth.manager.GlobalDataManager;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.core.util.utilcode.util.StringUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;

/**
 * @author zhangyu
 * @date 2019/2/18
 */
public class DialogPartLocationChoose extends Dialog {
    private int mColorN = Color.parseColor("#8fa3b7");
    private int mColorP = Color.parseColor("#f1b647");
    private Drawable mDrawableN;
    private Drawable mDrawableP;
    private List<PartLocationBean> mSelectedList;
    private Disposable mDisposable;
    private LocationAdapter mActionAdapter;
    private DialogLoader mDialogLoader;

    public DialogPartLocationChoose(Context context,
                                    final OnLocationChooseListener listener) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSelectedList = new ArrayList<>();
        mDrawableN = context.getResources().getDrawable(R.drawable.shape_item_operation_n);
        mDrawableP = context.getResources().getDrawable(R.drawable.shape_item_operation_c);
        View view = LayoutInflater.from(context).
                inflate(R.layout.dialog_location_choose, null);
        ((TextView) view.findViewById(R.id.tv_choose_action))
                .setText("选择位置");
        final TextView tvConfirm = view.findViewById(R.id.tv_confirm);
        final EditText editText = view.findViewById(R.id.et_input_position);
        view.findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加临时诊断
                String text = editText.getText().toString();
                if (!StringUtils.isEmpty(text)) {
                    int position = getBeanByName(text);
                    PartLocationBean partLocationBean;
                    if (position == -1) {
                        //没有相同名字
                        partLocationBean = new PartLocationBean();
                        partLocationBean.setSelected(true);
                        partLocationBean.setPositionCode("-1");
                        partLocationBean.setPositionName(text);
                        partLocationBean.setLocalTemp(true);
                        //0系统 1临时
                        partLocationBean.setIsTemp(-1);
                        mActionAdapter.addData(0, partLocationBean);
                        mSelectedList.add(partLocationBean);
                    } else {
                        //有同名
                        partLocationBean = mActionAdapter.getItem(position);
                        if (partLocationBean != null) {
                            if (!partLocationBean.isSelected()) {
                                partLocationBean.setSelected(true);
                                mSelectedList.add(partLocationBean);
                                mActionAdapter.notifyItemChanged(position);
                            }
                        }
                        setEnable(tvConfirm, true);
                        editText.setText("");
                    }
                }
            }
        });
        final RecyclerView recyclerView = view.findViewById(R.id.recycler_view_action);
        view.findViewById(R.id.iv_close).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
        view.findViewById(R.id.tv_confirm).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            if (mSelectedList != null && !mSelectedList.isEmpty()) {
                                StringBuilder selectedName = new StringBuilder();
                                StringBuilder selectedCode = new StringBuilder();
                                StringBuilder tempName = new StringBuilder();
                                PartLocationBean partLocationBeanNew = null;
                                for (PartLocationBean partLocationBean : mSelectedList) {
                                    if (partLocationBean.isLocalTemp()) {
                                        //本地临时需要提交到服务器
                                        tempName.append(partLocationBean.getPositionName()).append(",");
                                    } else {
                                        selectedName.append(partLocationBean.getPositionName()).append(",");
                                        selectedCode.append(partLocationBean.getPositionCode()).append(",");
                                    }
                                }
                                if (tempName.length() > 0) {
                                    tempName = new StringBuilder(tempName.substring(0, tempName.length() - 1));
                                }
                                if ((selectedName.length() > 0) && (selectedCode.length() > 0)) {
                                    selectedName = new StringBuilder(selectedName.substring(0, selectedName.length() - 1));
                                    selectedCode = new StringBuilder(selectedCode.substring(0, selectedCode.length() - 1));
                                    partLocationBeanNew = new PartLocationBean();
                                    partLocationBeanNew.setPositionName(selectedName.toString());
                                    partLocationBeanNew.setPositionCode(selectedCode.toString());
                                }
                                listener.onChoose(partLocationBeanNew, tempName.toString());
                            }
                        }
                        dismiss();
                    }
                });
        recyclerView.setLayoutManager(new

                GridLayoutManager(context, 4));
        mDisposable = RxRestClient.builder()
                .

                        url(Url.GetPartLocation)
                .

                        params("token", UserManager.getInstance().

                                getToken())
                .

                        success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                List<PartLocationBean> list =
                                        new ObjConverter<List<PartLocationBean>>().convert(response
                                                , new TypeReference<List<PartLocationBean>>() {
                                                });
                                if (list != null) {
                                    GlobalDataManager.getInstance().setPartLocationBeans(list);
                                }
                                mActionAdapter.setEmptyView(R.layout.view_search_empty,
                                        (ViewGroup) recyclerView.getParent());
                                mActionAdapter.setNewData(list);
                            }
                        })
                .

                        error(new IError() {
                            @Override
                            public void onError(int code, String msg) {

                            }
                        })
                .

                        build()
                .

                        post();
        recyclerView.setAdapter(mActionAdapter =
                new

                        LocationAdapter(R.layout.item_part_location, null));
        mActionAdapter.setEmptyView(R.layout.view_loading,
                (ViewGroup) recyclerView.getParent());
        RecyclerView.ItemAnimator itemAnimator = recyclerView.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        recyclerView.addOnItemTouchListener(new

                                                    OnItemChildClickListener() {
                                                        @Override
                                                        public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                                            PartLocationBean operationBean = (PartLocationBean) adapter.getItem(position);
                                                            if (view.getId() == R.id.tv_location) {
                                                                TextView tvLocation = ((TextView) view);
                                                                if (operationBean != null) {
                                                                    if (operationBean.isSelected()) {
                                                                        operationBean.setSelected(false);
                                                                        view.setBackground(mDrawableN);
                                                                        tvLocation.setTextColor(mColorN);
                                                                        if (mSelectedList != null) {
                                                                            mSelectedList.remove(operationBean);
                                                                        }
                                                                    } else {
                                                                        operationBean.setSelected(true);
                                                                        view.setBackground(mDrawableP);
                                                                        tvLocation.setTextColor(mColorP);
                                                                        if (mSelectedList != null) {
                                                                            mSelectedList.add(operationBean);
                                                                        }
                                                                    }
                                                                    setEnable(tvConfirm, !(mSelectedList == null || mSelectedList.isEmpty()));
                                                                }
                                                            }
                                                        }
                                                    });

        setEnable(tvConfirm, false);

        mDialogLoader = new

                DialogLoader(context);

        setContentView(view);
    }

    @Override
    public void dismiss() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    private int getBeanByName(String name) {
        List<PartLocationBean> beanList = mActionAdapter.getData();
        int position = -1;
        for (int i = 0; i < beanList.size(); i++) {
            PartLocationBean bean = beanList.get(i);
            if (bean.getPositionName().equals(name)) {
                position = i;
                break;
            }
        }
        return position;
    }

    private void setEnable(TextView tvConfirm, boolean isEnable) {
        tvConfirm.setBackgroundResource(isEnable ? R.drawable.shape_btn_operation_n :
                R.drawable.shape_btn_operation_t);
        tvConfirm.setTextColor(isEnable ? Color.parseColor("#333333") :
                Color.parseColor("#ffffff"));
        tvConfirm.setEnabled(isEnable);
    }

    private class LocationAdapter extends BaseQuickAdapter<PartLocationBean, BaseViewHolder> {

        LocationAdapter(int layoutResId, @Nullable List<PartLocationBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final PartLocationBean item) {
            helper.addOnClickListener(R.id.tv_location);
            helper.setText(R.id.tv_location, item.getPositionName());
            if (item.isSelected()) {
                helper.setTextColor(R.id.tv_location, mColorP);
                helper.setBackgroundRes(R.id.tv_location, R.drawable.shape_item_operation_c);
            } else {
                helper.setTextColor(R.id.tv_location, mColorN);
                helper.setBackgroundRes(R.id.tv_location, R.drawable.shape_item_operation_n);
            }
//            if (item.isLocalTemp() || item.getIsTemp() == 1) {
            if (item.isLocalTemp()) {
                helper.setVisible(R.id.iv_delete_part, true);
            } else {
                helper.setVisible(R.id.iv_delete_part, false);
            }
            helper.getView(R.id.iv_delete_part).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isLocalTemp()) {
                        //临时本地添加的零部件
                        remove(helper.getAdapterPosition());

                    } else {
                        //服务器临时
//                        deleteLocation(item, LocationAdapter.this,
//                                helper.getAdapterPosition());
                    }
                    if (item.isSelected()) {
                        //选中则删除选中
                        mSelectedList.remove(item);
                    }
                }
            });
        }
    }


    private void deleteLocation(final PartLocationBean partLocationBean,
                                final LocationAdapter actionAdapter, final int position) {
        mDialogLoader.showWarning("删除位置", "请确认", new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.changeToProgressType("正在提交");
                mDisposable = RxRestClient.builder()
                        .url(Url.DeleteTempLocation)
                        .params("token", UserManager.getInstance().getToken())
                        .params("positionCode", partLocationBean.getPositionCode())
                        .success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                mDialogLoader.clearDialog();
                                actionAdapter.remove(position);
                            }
                        })
                        .error(new IError() {
                            @Override
                            public void onError(int code, String msg) {
                                mDialogLoader.stopProgressWithFailed(msg, msg);
                            }
                        })
                        .build()
                        .post();
            }
        });
    }
    public Dialog measureSize(){
        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 720 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
        }
        return this;
    }
    public interface OnLocationChooseListener {
        public void onChoose(PartLocationBean partLocationBean, String temp);
    }

}
